<template>
  <div class="UploadList">
    <div class="UploadList-draggable">
      <VueDraggable class="UploadList-list" ref="el" v-model="fileList" :animation="150" @start="onStart"
        @update="onUpdate">
        <div class="UploadList-item" v-for="(item, index) in fileList" :key="item.id" @click="handleClick(item, index)">
          <img v-if="!getIncludeType(item.url)" :src="item.url" alt="">
          <video v-else :src="item.url" autoplay muted loop></video>
          <el-icon class="icon-close" @click="closeClick(item, index)">
            <Close />
          </el-icon>
        </div>
      </VueDraggable>

      <div class="UploadList-item-add" @click="addUpload">
        <el-icon class="upload-demo-icon">
          <Plus />
        </el-icon>
      </div>

      <VUpload ref="vUploadRef" @importData="importData" :limit="limit">
        <div class="upload-demo upload-img">
          <el-icon class="upload-demo-icon">
            <Plus />
          </el-icon>
        </div>
      </VUpload>
    </div>
    <el-progress v-if="showProgress && progress != 0" :percentage="progress" />
    <CView :dialog="dialog" :fileList="fileList" :clickIndex="clickIndex"></CView>
  </div>
</template>

<script setup lang="ts">
import { type UseDraggableReturn, VueDraggable } from 'vue-draggable-plus'
import { ElMessageBox } from 'element-plus'
import { Plus, Close } from '@element-plus/icons-vue'
import { VITE_APP_IMAGE_BASE_URL as baseImage } from '@/utils/base';
import { uploadFile, uploadFileList } from '@/api/file';
import { getIncludeType, clearFormData } from '@/utils/utils';

const props = defineProps({
  modelValue: {
    type: Array as any,
    default: () => [],
  },
  typeUploadList: {
    type: Array as any,
    default: () => [],
  },
  limit: {
    type: Number,
    default: 999,
  },
  showProgress: {
    type: Boolean,
    default: true,
  },
})
const fileList = ref(props.modelValue)
const emit = defineEmits(['update:modelValue'])
const { typeUploadList, showProgress } = toRefs(props)
const { limit } = toReactive(props)

const vUploadRef = ref();
const dataFormRef = ref(ElForm);
const el = ref<UseDraggableReturn>()
const progress = ref(0)
let timer: any = null

const formData = reactive({
  type: '1'
});

const dialog = reactive({
  visible: false,
  title: '预览'
})

function updateModelValue() {
  emit('update:modelValue', fileList.value)
}

function closeClick(item: any, index: any) {
  fileList.value.splice(index, 1)
  updateModelValue()
}

function addUpload() {
  handleImport()
  // openDialog()
}

function openDialog() {
  dialog.visible = true;
}

const clickCount = ref(0);
const clickIndex = ref(0);

const handleClick = (item: any, index: any) => {
  clickCount.value++;
  if (clickCount.value === 2) {
    // 这里执行你想要的操作
    openDialog()
    // 可选：重置计数器
    clickCount.value = 0;
    fileList.value.find((ele: any, eleIndex: any) => {
      if (ele.name === item.name) {
        clickIndex.value = eleIndex
      }
    })

  }
};
function handleSubmit() {
  handleImport()
  closeDialog()
}

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialog.visible = false;
}

/**
 * 重置表单
 */
function resetForm() {
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
    dataFormRef.value.clearValidate();
  }
  clearFormData(formData);
}

// 调用导入组件
function handleImport() {
  vUploadRef.value.importClick()
}

// 导入数据
function importData(fileObJ: any) {
  // formData.type == '1' ? 'image/png' : 'video/mp4'
  const formDa = new FormData();
  let fList = Object.values(fileObJ.files)
  let uploadStatus = true;

  if (limit === 1 && fList.length > 1) {
    ElMessage.warning(`只能上传一个LOGO！`);
    return
  }

  fList.forEach((ele: any, index: any) => {
    let typeMismatch = true;

    typeUploadList.value.forEach((typeEle: any) => {
      if (ele.type.includes(typeEle)) {
        typeMismatch = false;
      }
    });

    if (typeMismatch) {
      let str = typeUploadList.value.join(', ');
      ElMessage.warning(`文件必须为 ${str} 类型`);
      uploadStatus = false;
      return false; // 不符合要求的文件类型直接返回 false，打断循环
    }

    formDa.append('file', ele);
    formDa.append('contentType', ele.type);
  });

  if (!uploadStatus) {
    return;
  }

  timer = setInterval(() => {
    progress.value += 10
    if (progress.value >= 100) {
      progress.value = 99
    }
  }, 1000)

  uploadFileList(formDa).then((res: any) => {
    if (limit === 1) {
      fileList.value = []
    }
    res.data?.forEach((ele: any) => {
      fileList.value.push({ url: `${ele}`, type: formData.type, name: `${ele}` })
    })
    updateModelValue()
    uploadSuccess()
  }).catch(() => {
    uploadError()
  })
}

function uploadSuccess() {
  progress.value = 100
  clearInterval(timer)
  ElMessage.success('操作成功');
  setTimeout(() => {
    progress.value = 0
  }, 2000)
}

function uploadError() {
  progress.value = 0
  clearInterval(timer)
  ElMessage.error('操作失败');
}

const onStart = () => {
  console.log('start')
}

const onUpdate = (params: any) => {
  console.log('update', fileList.value)
  updateModelValue()
}

watchEffect(() => {
  fileList.value = [...props.modelValue];
});

// 在组件即将卸载前取消定时器  
onBeforeUnmount(() => {
  if (timer) {
    clearInterval(timer)
  }
});
</script>

<style scoped>
.upload-demo .upload-demo-img {
  width: 100px;
  height: 100px;
  display: block;
}

:deep(.el-upload-list) {
  display: none !important;
}

.upload-demo .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.upload-demo .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.upload-demo-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  text-align: center;
}
</style>

<style scoped lang="scss">
.upload-demo {
  display: none;
}

.UploadList {
  width: 700px;

  .UploadList-draggable {
    display: flex;
    flex-wrap: wrap;

    .UploadList-list {
      display: flex;
      flex-wrap: wrap;

      .UploadList-item {
        width: 150px;
        height: 150px;
        margin: 0 10px 10px;
        border-radius: 5px;
        border: 1px #dcdfe6 solid;
        position: relative;

        .icon-close {
          font-size: 20px;
          position: absolute;
          right: 3px;
          top: 3px;
          cursor: pointer;
          background: #dcdfe6;
          border-radius: 50%;
        }

        img {
          width: 100%;
          height: 100%;
        }

        video {
          width: 100%;
          height: 100%;
        }
      }
    }

    .UploadList-item-add {
      width: 150px;
      height: 150px;
      margin: 0 10px 10px;
      border-radius: 5px;
      border: 1px #dcdfe6 solid;
      position: relative;
      cursor: pointer;
    }

  }

}
</style>